//
//  ST_EditDailyMomentController.swift
//  btvideo
//
//  Created by mac on 2020/7/22.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import RealmSwift
import SwiftyUserDefaults

class ST_EditDailyMomentController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title_nav_btn.setTitleForAllStates("添加日常")
        
        right_nav_btn.setTitleForAllStates("发布")
        
        let img = UIImage.init(color: UIColor.init(hex: 0xDFE3E9)!, size: CGSize.init(width: 1, height: 1))
        right_nav_btn.setBackgroundImage(img, for: UIControl.State.disabled)
        let enableImg = UIImage.init(color: UIColor.init(hex: 0xFEC207)!, size: CGSize.init(width: 1, height: 1))
        right_nav_btn.setBackgroundImage(enableImg, for: UIControl.State.normal)
        right_nav_btn.cornerRadius = 30/2.0
        right_nav_btn.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.semibold)
        right_nav_btn.snp.remakeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(title_nav_btn)
            make.height.equalTo(30)
            make.width.equalTo(56)
        }
        right_nav_btn.isEnabled = false
        right_nav_btn.isHidden = false
        
         
        
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight+44, left: 0, bottom: 0, right: 0))
        }
        scrollView.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(ScreenHeight-statusBarHeight-44)
        }
        
        contentView.addSubview(cover_root_view)
        cover_root_view.snp.makeConstraints { (make) in
            make.height.width.equalTo(88)
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(15)
        }
        
        cover_root_view.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 20, left: 20, bottom: 20, right: 20))
        }
        
        
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(cover_root_view).offset(12)
            make.left.equalTo(cover_root_view.snp.right).offset(20)
            make.height.equalTo(33)
        }
        
        contentView.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.top.equalTo(cover_root_view).offset(54)
            make.left.equalTo(cover_root_view.snp.right).offset(20)
            make.height.equalTo(22)
        }
        
        contentView.addSubview(mainTitleLabel)
        mainTitleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(cover_root_view.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(15)
            make.height.equalTo(20)
        }
        
        
        contentView.addSubview(bottom_view)
        bottom_view.snp.makeConstraints { (make) in
            make.right.left.bottom.equalToSuperview()
            make.height.equalTo(168-10+BTSafeAreaBottom)
        }
        
        let offset:CGFloat = 70/2.0/375.0*ScreenWidth
        
        bottom_view.addSubview(video_btn)
        video_btn.snp.makeConstraints { (make) in
            make.width.equalTo(80)
            make.height.equalTo(80+12+20)
            make.right.equalTo(bottom_view.snp.centerX).offset(-offset)
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-30)
        }
        
        bottom_view.addSubview(photo_btn)
        photo_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(video_btn)
            make.left.equalTo(bottom_view.snp.centerX).offset(offset)
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-30)
        }
        
        contentView.addSubview(text_view_container)
        text_view_container.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(mainTitleLabel.snp.bottom).offset(10)
            make.bottom.equalTo(bottom_view.snp.top).offset(-10)
        }
        
        text_view_container.addSubview(textView)
        textView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 15, left: 15, bottom: 7, right: 15))
        }
        
        text_view_container.addSubview(text_place_holder_label)
        
        text_place_holder_label.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(7)
            make.left.equalTo(textView).offset(4)
            make.right.equalTo(textView)
        }
        
        text_view_container.addSubview(current_text_count_label)
        current_text_count_label.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-5)
            make.bottom.equalToSuperview().offset(-5)
        }
    }
    
    override func right_click() {
        
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        guard let m = model , let remark = textView.text else{
            self.toast(text: "必须填写描述哦")
            return
        }
        
        
        if remark.removingWhitespaces().count < 1{
            self.toast(text: "不能全是空格哦")
            return
        }
        
        let task = ST_PushDailyTask()
        task.dailyId = m.id.string
        task.dailyName = m.name
        task.accountId = Defaults[.currentUserID]
        task.remark = remark
        
        

        if let url = self.preview_video_view.videoURL{
            
            task.videoPath = url.path
            
            guard let imgPath = self.preview_video_view.thumbnail_image_path, var coverImgPath = SC.push_peculiarity_directory else{
                return
            }
            
            coverImgPath.appendPathComponent(imgPath)
            
            guard let img  = UIImage(contentsOfFile: coverImgPath.path) else{
                return
            }
            
            
            let duration = AVURLAsset(url: url).duration.seconds
            
            task.coverImagePath = imgPath
            
            task.imageWidth = img.size.width.double
            
            task.imageHeight = img.size.height.double
            
            task.videoDuration = duration.int
            
            self.finalStep(task: task)
            
        }else if let imageArray = self.previewImagesView.pictures{
            
            for (idx,imgRes) in imageArray.enumerated() {
                
                let img = imgRes.image
                
                let imgPath = img.compress_with_cache_s_d_image()
                
                let resource = ST_PushDailyTaskResource()
                
                resource.taskId = task.id
                
                resource.path = imgPath
                
                resource.imageWidth = img.size.width.double
                
                resource.imageHeight = img.size.height.double
                
                resource.sortInTask = idx
                
                task.resources.append(resource)
                    
            }
        
            task.resources.forEach({$0.taskResourceCount = task.resources.count })
            
            self.finalStep(task: task)
          
        }else{
            self.finalStep(task: task)
        }
        
        
        
    }
    
    fileprivate func finalStep(task:ST_PushDailyTask){
        
        let realm = try! Realm()
        
        try! realm.write {
            realm.add(task)
        }
        
        ST_PushDailyCoordinator.shared.task_loop()
        
        UIView.animate(withDuration: 0, animations: {
            self.navigationController?.popToRootViewController(animated: true)
        }) { (f) in
            
            UIApplication.shared.tainMainWindow?.rootViewController?.dismiss(animated: true) {
                ST_BTLaunchController.shared.scroll_to_page(tab: .recommend)
            }
        }
    }
    
//    MARK: - Properties
    var model:ST_DailBaseModel?{
        didSet{
            
            guard let m = model else { return  }
            
            cover_image_view.pin_setImage(from: m.image.url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            titleLabel.text = m.name
            
            let contentStr = NSMutableAttributedString.init(string: m.publishNum.st_number_description())
            
            contentStr.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.init(hex: 0x333333)!,NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)], range: NSRange.init(location: 0, length: contentStr.length))
            
            let contentUnitStr = NSMutableAttributedString.init(string: "条日常")
            
            contentUnitStr.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.init(hex: 0xACB4C0)!,NSAttributedString.Key.baselineOffset:1,NSAttributedString.Key.font:UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)], range: NSRange.init(location: 0, length: contentUnitStr.length))
            
            contentStr.append(contentUnitStr)
            
            let lookStr = "   " + m.lookNum.st_number_description()
            let contentLookStr = NSMutableAttributedString.init(string: lookStr)
            
            contentLookStr.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.init(hex: 0x333333)!,NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)], range: NSRange.init(location: 0, length: contentLookStr.length))
            
            let contentLookUnitStr = NSMutableAttributedString.init(string: "人在看")
            
            contentLookUnitStr.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.init(hex: 0xACB4C0)!,NSAttributedString.Key.baselineOffset:1,NSAttributedString.Key.font:UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)], range: NSRange.init(location: 0, length: contentLookUnitStr.length))
            
            contentLookStr.append(contentLookUnitStr)
            
            contentStr.append(contentLookStr)
            
            content_label.attributedText = contentStr
        }
    }
    
    fileprivate lazy var scrollView:UIScrollView = {
       let control = UIScrollView()
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.alwaysBounceVertical = true
        return control
    }()
    
    fileprivate lazy var contentView:UIView = {
       let control = UIView()
        return control
    }()
    
    
    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        return control
    }()
    
    
    fileprivate lazy var cover_root_view:UIView = {
        let control = UIView()
        control.cornerRadius = 15
        control.backgroundColor = UIColor.init(hex: 0xF5F8FA)
        return control
    }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 24, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        return control
    }()
    
    fileprivate lazy var mainTitleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "正文"
        control.textColor = UIColor.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var bottom_view:UIView = {
        let control = UIView()
        return control
    }()

    fileprivate lazy var video_btn:ST_VerticalButton = {
            
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 0, bottom: 12+20, right: 0)
        control.title_bottom_offset = 0
        let attrString = NSMutableAttributedString(string: "视频")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor.init(hex: 0x333333)!]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.setTitle(attrString, for: UIControl.State.normal)
        control.setImage(ST_ImageUtils.imageName("首页_bot_视频")!, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(record_btn_click), for: .touchUpInside)
        return control
    }()

    fileprivate lazy var photo_btn:ST_VerticalButton = {
            
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 0, bottom: 12+20, right: 0)
        control.title_bottom_offset = 0
        let attrString = NSMutableAttributedString(string: "图片")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor.init(hex: 0x333333)!]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.setTitle(attrString, for: UIControl.State.normal)
        
        control.setImage(ST_ImageUtils.imageName("首页_icon_相册")!, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(photo_btn_click), for: .touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var text_view_container:UIView = {
       let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "#F5F8FA")
        control.cornerRadius = 15
        return control
    }()

    fileprivate lazy var textView:UITextView = {
       let control = UITextView()
        control.backgroundColor = .clear
        control.textColor = UIColor.init(hexString: "#61666F")
        control.tintColor = UIColor.init(hexString: "#61666F")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.delegate = self
        return control
    }()
    
    
    fileprivate let place_holder_attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
    
    fileprivate lazy var normal_place_holder_string:NSAttributedString = {
        
        let attrString = NSMutableAttributedString(string: "文案写得好，互动少不了~认真写下此刻的想法哦！")
        
         attrString.addAttributes(place_holder_attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }()
    
    
    fileprivate lazy var text_place_holder_label:UILabel = {
       
        let control = UILabel()
      
        control.attributedText = normal_place_holder_string
        
        control.numberOfLines = 0
        
        return control
    }()
    
    fileprivate var  maxCount = 400
    
    fileprivate lazy var current_text_count_label:UILabel = {
       
        let control = UILabel()
        control.textColor = UIColor.init(hex: 0xACB4C0)
        control.font = UIFont.systemFont(ofSize: 12)
        control.text = "0/\(maxCount)"
        return control
    }()
    
//    MARK: Preview Video
    fileprivate lazy var preview_video_view:ST_EditDailyMomentVideoItemView = {
        let control = ST_EditDailyMomentVideoItemView()
        control.clear_closure = {[weak self] in
            self?.bottom_view.isHidden = false
            self?.preview_video_view.isHidden = true
        }
        return control
    }()
    
//    MARK: PreView Images
    fileprivate var selected_image_ids = [String]()
    
    fileprivate lazy var previewImagesView:ST_EditDailyMomentImagesView = {
        let control = ST_EditDailyMomentImagesView()
        control.append_closure = {[weak self] in
            self?.photo_btn_click()
        }
        
        control.deleteClosure = {[weak self] picture in
            
            self?.selected_image_ids.removeAll(picture.identifier)
            
            self?.refresh_bottom_view()
        }
        
        return control
    }()
    
}

extension ST_EditDailyMomentController:UITextViewDelegate{
    
    func textViewDidChange(_ textView: UITextView) {
        text_place_holder_label.isHidden = !textView.text.isEmpty
        
        right_nav_btn.isEnabled = !textView.text.isEmpty
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        
        text_place_holder_label.isHidden = !textView.text.isEmpty
        
        right_nav_btn.isEnabled = !textView.text.isEmpty
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        guard var animal = textView.text else{
            return true
        }
        
        if let idxRange = Range.init(range, in: animal){
            
            animal.replaceSubrange(idxRange, with: text)
            
            var residueCount = maxCount - animal.count
            
            if residueCount < 0{
                residueCount = 0
            }
            
            var displayCount = animal.count
            
            if displayCount > maxCount{
                displayCount = maxCount
            }
            
            current_text_count_label.text = "\(displayCount)/\(maxCount)"
            
            return animal.count <= maxCount
            
        }else{
            return true
        }
    }
    
}

//MARK: - Event
extension ST_EditDailyMomentController{

    
    fileprivate func refresh_bottom_view(){
        
        if self.selected_image_ids.count < 1{
            self.previewImagesView.isHidden = true
            self.bottom_view.isHidden = false
        }
        
    }
    
    @objc func photo_btn_click(){
        
        
        let imagePicker = ST_JVImagePickerController()
        imagePicker.picker_style = .image
        imagePicker.overCurrentContext = true
        imagePicker.maxImagesCount = 4
        imagePicker.normal_selected_id_array = self.selected_image_ids
        
        GlobalPresent(toController: imagePicker)

        imagePicker.picker_images_closure = {[weak self] images in
            
            self?.bottom_view.isHidden = true
            
            guard let strongSelf = self else { return  }
            
            if strongSelf.previewImagesView.superview == nil{
                strongSelf.contentView.addSubview(strongSelf.previewImagesView)
                strongSelf.previewImagesView.snp.makeConstraints { (make) in
                    make.height.equalTo(ST_EditDailyMomentImagesView.height)
                    make.bottom.equalToSuperview().offset(-64-BTSafeAreaBottom)
                    make.right.left.equalToSuperview()
                }
            }
            
            strongSelf.selected_image_ids = images.map({ (id,img) -> String in
                return id
            })
            
            strongSelf.previewImagesView.pictures = images
            
            strongSelf.previewImagesView.isHidden = false
            
        }
        
    }
    @objc func record_btn_click(){
        
        let vc = ST_JVImagePickerController()
                
        vc.picker_style = .video
                
        vc.overCurrentContext = true
     
        
        vc.picker_video_closure = {[weak self] url,seconds in
            
            let filename = UUID().uuidString+".mp4"
            
            guard var videoPath = SC.push_peculiarity_directory else { return }
            
            videoPath.appendPathComponent(filename)
            
            do {
                try FileManager.default.copyItem(at: url, to: videoPath)
            } catch (let error) {
                print("Cannot copy item at \(url) to \(videoPath): \(error)")
                return
            }

            
            self?.bottom_view.isHidden = true
            
            
            guard let strongSelf = self else { return  }
            
            if strongSelf.preview_video_view.superview == nil{
                strongSelf.contentView.addSubview(strongSelf.preview_video_view)
                strongSelf.preview_video_view.snp.makeConstraints { (make) in
                    make.width.height.equalTo(78)
                    make.bottom.equalToSuperview().offset(-64-BTSafeAreaBottom)
                    make.left.equalToSuperview().offset(15)
                }
            }
            
            strongSelf.preview_video_view.videoURL = videoPath
            
            strongSelf.preview_video_view.isHidden = false
            
        }
        
        GlobalPresent(toController: vc)
       
    }
}
